<template>
  <view class="main">
    <view class="title-box">"{{ titleName }}"的对话</view>
    <image :src="picture" mode="widthFix" class="banner-img"></image>
    <view class="wrap">
      <!-- <text
      class="text"
      :class="activeWord == index && answering ? 'activeText' : ''"
      v-for="(item, index) in answerList"
      :key="index"
      >{{ item }}</text
    > -->
      <text
        class="text"
        v-for="(item, index) in asList"
        :key="index"
        :class="
          currentTime > item.startSeconds && currentTime < item.endSeconds
            ? 'activeText'
            : ''
        "
        >{{ item.text }}</text
      >
      <view class="bottom-bar">
        <view class="left" @tap.stop="onPlayIconClick">
          <image src="@/static/imgs/icons/read_all.png" mode="widthFix"></image>
          <text>英语朗读</text>
        </view>
        <view class="right">
          <button open-type="share">
            <image
              src="@/static/imgs/icons/share_icon.png"
              mode="widthFix"
            ></image>
          </button>
          <image
            style="margin-left: 12rpx"
            src="@/static/imgs/icons/copy_icon.png"
            mode="widthFix"
            @tap.stop="onCopyIconClick"
          ></image>
        </view>
      </view>
      <view
        class="bottom-bar"
        style="margin-top: 20rpx; padding-left: 2rpx"
        @tap.stop="jumpBreakAnswerPage"
      >
        <view class="left">
          <image
            src="@/static/imgs/icons/read_some.png"
            mode="widthFix"
            style="width: 36rpx"
          ></image>
          <text>分段陪练</text>
        </view>
      </view>
    </view></view
  >
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { tnNavPage } from '@tuniao/tnui-vue3-uniapp/utils'
import { onLoad, onHide, onUnload } from '@dcloudio/uni-app'
import { getSceneDetailById } from '@/services/api'
import { Base64 } from 'js-base64'
import { useWebsocket } from '@/hooks'
import srtParser2 from 'srt-parser-2'
var plugin = requirePlugin('WechatSI')
let manager = plugin.getRecordRecognitionManager()

const innerAudioContext = uni.createInnerAudioContext()
const answer = ref('')
const audioSrc = ref('')
const titleName = ref('')
const answerList = ref([] as any)
const activeWord = ref()
const answering = ref(false)
const currentTime = ref(0)
const picture = ref('')
const asList = ref([] as any)
const audio = ref('')
const playing = ref(false)
let music = uni.createInnerAudioContext()
// music.src =
//   'https://api.chongli.maiyajia.com/uploads/01_hello_lesson1_4980ad0a58.MP3'
const onPlayIconClick = () => {
  if (playing.value) {
    music.pause()
    playing.value = false
  } else {
    music.play() //执行播放
    music.onPlay(() => {
      console.log('开始播放')
      playing.value = true
    })
    music.onTimeUpdate(() => {
      currentTime.value = music.currentTime
      console.log(currentTime.value)
    })
    music.onEnded(() => {
      //播放结束
      music.stop()
      playing.value = false
      console.log('播放结束')
    })
  }
}
const { handleCloseVideo, handlePlayVideo, webSocketSendMp3 } = useWebsocket()
const str = ref('')
var parser = new srtParser2()

onLoad((options) => {
  console.log(options)
  // var srt_string = parser.toSrt(srt_array)
  // console.log(srt_string)
  // asList.value.forEach((item) => {
  //   item.startTime = setTime(item.startTime)
  //   item.endTime = setTime(item.endTime)
  // })
  const { id, name, answerZh } = options
  if (id) {
    getData(id)
  }
  if (name) {
    titleName.value = name
  }
  if (answerZh) {
    onTranslate(answerZh)
  }
})

onHide(() => {
  music.stop()
})
onUnload(() => {
  music.stop()
})
//将'00:01:60,888'格式时间转化为秒
const setTime = (time) => {
  let aTime = time.split(',')[0]
  let sTime = '.' + time.split(',')[1]
  let s = aTime.split(':')[0]
  let f = aTime.split(':')[1]
  let m = aTime.split(':')[2]
  let allTime = Number(s * 3600 + f * 60 + Number(m) + sTime)
  return allTime
}
const getData = (id) => {
  getSceneDetailById(id).then((res) => {
    const { code, data } = res
    if (code === 0) {
      // // answer.value = Base64.decode(data.content) //Base64解密
      // answer.value = data.content
      // // answer.value.replace(/[\n\r]/g, '<br>')
      // answerList.value = answer.value.split(/\n/)
      str.value = data.subtitles
      asList.value = parser.fromSrt(str.value)
      console.log('uuuuu', asList.value)
      music.src = data.audio
      audio.value = data.audio
      picture.value = data.picture
    }
  })
}

const jumpBreakAnswerPage = () => {
  let encoded = Base64.btoa(
    unescape(encodeURIComponent(JSON.stringify(asList.value)))
  )
  tnNavPage(
    `/home-page/agent/break-answer?answerEn=${encoded}&source=2&audio=${audio.value}`
  )
}

//中文翻译成英文
const onTranslate = (answerZh) => {
  plugin.translate({
    lfrom: 'zh_CN',
    lto: 'en_US',
    content: answerZh,
    success: function (res) {
      if (res.retcode == 0) {
        answer.value = res.result
        outputText(answer.value)
      } else {
        console.warn('翻译失败', res)
      }
    },
    fail: function (res) {
      console.log('网络失败', res)
    },
  })
}

//流式输出文字
const outputText = (text) => {
  var index = 0
  const streamOutput = () => {
    if (index < text.length) {
      var currentText = text.substring(0, index + 1)
      answer.value = currentText
      index++
    } else {
      clearInterval(timer)
    }
  }
  let timer = setInterval(streamOutput, 20)
}

//英文转语音
// const textToSpeech = () => {
//   return new Promise((resolve, reject) => {
//     plugin.textToSpeech({
//       lang: 'en_US',
//       tts: true,
//       content:
//         answer.value.length < 900 ? answer.value : answer.value.slice(0, 900),
//       success: function (res) {
//         console.log('succ tts', res.filename)
//         audioSrc.value = res.filename
//         resolve()
//       },
//       fail: function (res) {
//         console.log('fail tts', res)
//       },
//     })
//   })
// }

const stopAudio = () => {
  innerAudioContext.stop()
}

//讯飞的语音播放接口
// const onPlayIconClick = async () => {
//   // Chinese中文 | English英文
//   answerList.value = answer.value.split(/\n/)
//   console.log(answerList.value)
//   playAudio(0)
// }
//利用递归函数去遍历每一句话的播放
// const playAudio = async (sum: number) => {
//   try {
//     let answerIndex = sum
//     if (answerIndex < answerList.value.length) {
//       // 发送消息获取音频并处理
//       const res = await webSocketSendMp3(
//         answerList.value[answerIndex],
//         'English'
//       )
//       let audioDataArray = [] as any
//       res.forEach((item, index) => {
//         const arrayBuffer = wx.base64ToArrayBuffer(item)
//         const newBuffer = new Uint8Array(arrayBuffer)
//         audioDataArray.push(...newBuffer)
//       })
//       const uint8Array = new Uint8Array(audioDataArray)
//       const audioUrl = wx.createBufferURL(uint8Array.buffer)

//       // 播放音频并处理播放状态,播放该句子就会高亮，该句子的索引
//       activeWord.value = answerIndex
//       answering.value = true
//       await handlePlayVideo(audioUrl)

//       // 继续播放下一句
//       await playAudio(answerIndex + 1)
//     } else {
//       answering.value = false
//     }
//   } catch (error) {
//     console.error('播放音频时出错：', error)
//     // 可以添加错误处理逻辑，比如重试播放或提醒用户
//   }
// }
const onCopyIconClick = () => {
  uni.setClipboardData({
    data: answer.value,
    success: function () {},
  })
}

const onZanIconClick = () => {
  uni.showToast({
    title: '已赞',
    duration: 2000,
  })
}

const onCaiIconClick = () => {
  uni.showToast({
    title: '已踩',
    duration: 2000,
  })
}
</script>

<style lang="scss" scoped>
.problem-title {
  margin: 40rpx auto;
  text-align: center;
  font-size: 26rpx;
  font-weight: bold;
  font-family: 'tuniao-xiaowei';
}
.wrap {
  width: 100%;
  padding: 30rpx 20rpx;
  border-radius: 0 22rpx 22rpx 22rpx;
  background-color: #fdfdfd;
  font-size: 28rpx;
  font-family: 'tuniao-xiaowei';
  clear: both;
  color: #191919;
}
image {
  width: 50rpx;
}
.bottom-bar {
  margin-top: 40rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .left {
    image {
      vertical-align: middle;
      margin-right: 14rpx;
      width: 40rpx;
    }
  }
  .left {
    text {
      vertical-align: middle;
      color: #4b49e8;
      font-size: 24rpx;
    }
  }
  .right {
    display: flex;
    button {
      background-color: #fff;
      width: 44rpx;
      margin: 0;
      padding: 0;
      position: relative;
      margin-right: 12rpx;
      image {
        position: absolute;
        top: 0;
        left: 0;
      }
    }
    image {
      margin-right: 18rpx;
    }
  }
}
.title-box {
  padding: 10rpx 24rpx;
  margin: 20rpx;
  text-align: right;
  font-size: 28rpx;
  line-height: 44rpx;
  color: #fff;
  text-align: left;
  border-radius: 30rpx 0 30rpx 30rpx;
  float: right;
  background: linear-gradient(90deg, #4b49e8 0%, #6b8bfb 100%);
  border-image: linear-gradient(
      180deg,
      rgba(255, 255, 255, 1),
      rgba(255, 255, 255, 0.38)
    )
    2 2;
  max-width: 90%;
  float: right;
}
.activeText {
  color: #4b49e8;
  font-size: 30rpx;
  font-weight: bold;
}

.main {
  width: 100%;
  min-height: 100%;
  padding: 32rpx;
  .banner-img {
    width: 100%;
    margin-bottom: 24rpx;
  }
  .text {
    display: block;
    line-height: 44rpx;
    font-size: 28rpx;
    color: #191919;
  }
}
</style>
